package com.atguigu.educenter.controller;

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.educenter.utils.ConstantWxUtils;
import com.atguigu.educenter.utils.HttpClientUtils;
import com.atguigu.servicebase.exceptionhandler.GuLiException;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@Controller
@RequestMapping("api/ucenter/wx")
//@CrossOrigin
public class WxApiController {
    @Autowired
    private UcenterMemberService ucenterMemberService;
    @GetMapping("callback")
    public String callback(String code,String state){
        //获取code（临时票据）
        System.out.println("code:"+code+",state:"+state);
        //通过code，请求微信提供的固定地址得到两个值，access_token,openid
        //向认证服务器发送请求换取access_token
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";
        //拼接三个参数
        String accessTokenUrl = String.format(
                baseAccessTokenUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,
                code);
        //通过拼接好的地址请求，得到两个值，access_token,openid
        //使用httpClient工具类
        String accessTokenInfo = null;
        try {
            accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            //System.out.println("accessTokenInfo:"+accessTokenInfo);
        } catch (Exception e) {
            throw new GuLiException(20001, "获取access_token失败");
        }
        //从accessTokenInfo字符串中获取access_token和openid
        //把accessTokenInfo转换map集合，根据map里面key获取对应值
        //使用json转换工具gson
        Gson gson = new Gson();
        HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
        String access_token = (String) mapAccessToken.get("access_token");
        String openid = (String) mapAccessToken.get("openid");
        //把扫描人的信息加到数据库中
        //判断数据库中是否有扫描人的openid，没有则加入
        UcenterMember member = ucenterMemberService.getOpenIdMember(openid);
        if(member == null){ //member为空，表没有相同的微信数据，进行添加，有则直接登录
            //拿着access_token和openid去请求微信提供的地址，获取扫描人的信息
            //访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(
                    baseUserInfoUrl,
                    access_token,
                    openid
            );
            String userInfo = null;
            try {
                userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("userInfo:"+userInfo);
            } catch (Exception e) {
                throw new GuLiException(20001,"获取用户信息失败");
            }
            //从userInfo字符串中获取用户的信息，使用gson转换为map集合，在获取信息
            HashMap mapUserInfo = gson.fromJson(userInfo, HashMap.class);
            String nickname = (String) mapUserInfo.get("nickname");
            String headimgurl = (String) mapUserInfo.get("headimgurl");
            member = new UcenterMember();
            member.setNickname(nickname);
            member.setAvatar(headimgurl);
            member.setOpenid(openid);
            ucenterMemberService.save(member);
        }
        String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
        //最后：返回首页面，并将存储用户信息的token字符串根据路径传递
        return "redirect:http://localhost:3000?token="+token;
    }

    @GetMapping("login")
    public String getWxCode(){
        // 微信开放平台授权baseUrl %s相当于?代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        // 回调地址 对redirect_url进行URLEncoder编码
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //设置%s的值
        String url = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "imhelen"
        );
        return "redirect:" + url;

    }
}
